<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="购物车案例" placeholder fixed />
    <!-- 单元格 -->
    <van-cell-group style="margin-bottom: 50px">
      <van-cell v-for="item in list" :key="item.id">
        <template>
          <div class="goodsItem">
            <van-checkbox v-model="item.goods_state" shape="square"
              ><van-image
                width="120"
                height="120"
                fit="cover"
                :src="item.goods_img"
            /></van-checkbox>
            <div class="goodsContent">
              <h3>
                {{ item.goods_name }}
              </h3>
              <div style="display: flex; justify-content: space-between">
                <span style="color: red">¥{{ item.goods_price }}</span>
                <van-stepper
                  v-model="item.goods_count"
                  theme="round"
                  button-size="22"
                  disable-input
                />
              </div>
            </div>
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 底部 -->
    <van-submit-bar :price="totalPrice" :button-text="totalCount">
      <van-checkbox v-model="chkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import axios from "axios";
export default {
  computed: {
    totalPrice() {
      let sum = 0;
      this.list.forEach((v) => {
        if (v.goods_state == true) {
          sum += v.goods_count * v.goods_price;
        }
      });
      return sum * 100;
    },
    chkAll: {
      set(val) {
        this.list.forEach((v) => (v.goods_state = val));
      },
      get() {
        return this.list.every((v) => v.goods_state);
      },
    },
    totalCount() {
      // 统计数量
      let count = 0;
      this.list.forEach((v) => {
        // 判断是否为true,代表选中了
        if (v.goods_state == true) {
          count += v.goods_count;
        }
      });
      return `结算(${count}件)`;
    },
  },
  data() {
    return {
      list: [],
    };
  },
  async created() {
    const res = await axios({
      url: "https://www.escook.cn/api/cart",
    });
    console.log(res);
    this.list = res.data.list;
  },
};
</script>

<style>
.goodsItem {
  display: flex;
}
.goodsContent {
  flex: 1;
  margin-left: 10px;
}
</style>